﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Comdiv.QWeb.Utils;

namespace Comdiv.QWeb.Remoting {
	public class QWebQuery {
		private QWebStandardRender _render;
		private string _renderName;

		public QWebQuery() {
			Render = QWebStandardRender.XML;
			Headers = new Dictionary<string, string>();
		}

		public string Action { get; set; }

		public QWebStandardRender Render {
			get { return _render; }
			set {
				_render = value;
				RenderName = _render.ToString().ToLower();
			}
		}

		public IDictionary<string, string> Headers { get; set; }

		public string RenderName {
			get { return _renderName; }
			set {
				_renderName = value;
				QWebStandardRender r;
				var st = Enum.TryParse(_renderName, true, out r);
				_render = st ? r : QWebStandardRender.Custom;
			}
		}

		public object Parameters { get; set; }

		public WebRequest CreateWebRequest(string urlbase) {
			var url = urlbase + "/" + Action.Replace(".", "/") + "." + RenderName.ToLower() + ".qweb";
			if (null != Parameters) {
				var sb = new StringBuilder();
				sb.Append("?");
				if (Parameters is IDictionary<string, object>) {
					foreach (var o in ((IDictionary<string, object>) Parameters)) {
						sb.Append("&");
						sb.Append(Uri.EscapeUriString(o.Key));
						sb.Append("=");
						sb.Append(Uri.EscapeUriString(o.Value.toStr()));
					}
				}
				else if (Parameters is IDictionary<string, string>) {
					foreach (var o in ((IDictionary<string, string>) Parameters)) {
						sb.Append("&");
						sb.Append(Uri.EscapeUriString(o.Key));
						sb.Append("=");
						sb.Append(Uri.EscapeUriString(o.Value));
					}
				}
				else {
					var props = Parameters.GetType().GetProperties();
					foreach (var p in props) {
						sb.Append("&");
						sb.Append(Uri.EscapeUriString(p.Name));
						sb.Append("=");
						sb.Append(Uri.EscapeUriString(p.GetValue(Parameters, null).toStr()));
					}
				}
				url += sb.ToString();
			}
			var result = WebRequest.Create(url);
			foreach (var header in Headers) {
				result.Headers.Add(header.Key, header.Value);
			}
			return result;
		}

		public void Setup(string urlbase, QWebContext context) {
			context.Uri = new Uri(urlbase + Action.Replace(".", "/") + "." + RenderName.ToLower() + ".qweb");
			if (null != Parameters) {
				if (Parameters is IDictionary<string, object>) {
					foreach (var o in ((IDictionary<string, Object>) Parameters)) {
						context.Set(o.Key, o.Value);
					}
				}
				else if (Parameters is IDictionary<string, string>) {
					foreach (var o in ((IDictionary<string, string>) Parameters)) {
						context.Set(o.Key, o.Value);
					}
				}
				else {
					var props = Parameters.GetType().GetProperties();
					foreach (var p in props) {
						context.Set(p.Name, p.GetValue(Parameters, null));
					}
				}
			}
		}
	}
}